package com.bys.security;

import com.bys.constant.CrmSystemConstant;

import com.bys.system.vo.LoginUserHelper;
import com.bys.util.JwtUtil;
import com.bys.util.RespUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * 认证解析 token 过滤器
 */
@Slf4j
public class TokenAuthFilter extends OncePerRequestFilter {
    private StringRedisTemplate redisTemplate;
    public TokenAuthFilter() {
    }

    public TokenAuthFilter(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        log.info("请求的接口 {}", request.getRequestURI());

        UsernamePasswordAuthenticationToken authToken = getAuth(request);
        if(authToken != null){
            SecurityContextHolder.getContext().setAuthentication(authToken);
        }
        filterChain.doFilter(request,response);

    }

    private UsernamePasswordAuthenticationToken getAuth(HttpServletRequest request) {
        try {
            UsernamePasswordAuthenticationToken auth = null;
            String requestURI = request.getRequestURI();
            String token = request.getHeader("token");
            if (StringUtils.isNotBlank(token)) {
                String username = JwtUtil.getUsername(token);
                Long userId = JwtUtil.getUserId(token);
                if (StringUtils.isNotBlank(username)) {
                    LoginUserHelper.setUserId(userId);
                    LoginUserHelper.setUsername(username);
                    String permissions = redisTemplate.opsForValue().get(token);
                    ObjectMapper objMapper = new ObjectMapper();
                    List<Map<String,String>> authList =  objMapper.readValue(permissions,List.class);
                    Set<CrmGrantedAuthority> pers = new HashSet<>();
                    authList.forEach( a ->{
                        pers.add(new CrmGrantedAuthority(a.get(CrmSystemConstant.REDIS_AUTH)));
                    });
                    return new UsernamePasswordAuthenticationToken(username, null,pers);
                }
            }
            return auth;
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

}
